package com.rentalcar.rental_car.service.impl;

import com.rentalcar.rental_car.dao.RoleMapper;
import com.rentalcar.rental_car.entity.Result;
import com.rentalcar.rental_car.entity.Role;
import com.rentalcar.rental_car.service.RoleService;
import com.rentalcar.rental_car.utils.JwtUtils;
import com.rentalcar.rental_car.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Role> getRoleAll() {

        return roleMapper.getRoleAll();
    }

    @Override
    public List<Role> selectByName(String rname) {

        return roleMapper.selectByName(rname);
    }

    @Override
    public Result add(Role role) {

        List<Role> roleList = roleMapper.selectByName(role.getRname());
        if(roleList.size()>0)
            return Result.fail("账号已存在");
        if ("".equals(role.getRname())||"".equals(role.getPassword()))
            return Result.fail("账号密码不能为空");
        role.setPassword(MD5.encoding(role.getPassword()));
        roleMapper.add(role);
        return Result.success();
    }

    @Override
    public int update(Role role) {

        return roleMapper.update(role);
    }

    @Override
    public int delete(Role role) {

        return roleMapper.delete(role);
    }

    @Override
    public Result loginCheck(Role role) {

        role.setPassword(MD5.encoding(role.getPassword()));
        Role c = roleMapper.loginCheck(role);

        if (c == null) {
            return Result.fail("账号密码错误");
        }
        HashMap<String, Object> data = new HashMap<>();
//        try {
//            HashMap<String, String> payload = new HashMap<>();
//            payload.put("rname", c.getRname());
//            String token = TokenUtils.getToken(payload);
//            c.setToken(token);
//            roleMapper.updateToken(c);
//            data.put("roleKey",c.getRoleKey());
//            data.put("rname", c.getRname());
//            data.put("token", token);
//            return Result.success(data);
//        } catch (Exception e) {
//            return Result.fail("登录失败");
//        }
        try {
            data.put("roleKey", c.getRoleKey());
            data.put("rname", c.getRname());
            data.put("phone", c.getPhone());
            String jwt = JwtUtils.generateJwt(data);
            c.setToken(jwt);
            roleMapper.updateToken(c);
            return Result.success(c);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("登录失败");
        }
    }

    @Override
    public Result logOut(Role role) {

        Role c = roleMapper.selectByName(role.getRname()).get(1);
        c.setToken(null);
        if (roleMapper.updateToken(c)==1){
            return Result.success();
        }
        return Result.fail("退出失败");
    }

}
